package com.woniu.service.util;

import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;
@Slf4j
public class UserTokenUtil {

    private static String token_key = "token";
    private static String cookike_key = "token";

    public static String createUserToken(String account, HttpServletResponse response, StringRedisTemplate stringRedisTemplate){

        String token = JwtUtil.createTokenSingleInfo(30, token_key, account);
        CookieUtils.addCookie(response,cookike_key,token,false);

        stringRedisTemplate.opsForValue().set(token,account,60, TimeUnit.MINUTES);

        return token;
    }


    public static String getUserAccount(HttpServletRequest request){

        String tokenFromCookie = CookieUtils.getCookieValueByName(request, cookike_key);

        String account = JwtUtil.parseValueWithoutException(tokenFromCookie, token_key);

        return account;
    }

    public static void deleteUserToken(HttpServletResponse response,HttpServletRequest request,StringRedisTemplate stringRedisTemplate){

        CookieUtils.addCookie(response,cookike_key,"xxxx",true);

        String tokenFromCookie = CookieUtils.getCookieValueByName(request, cookike_key);
        stringRedisTemplate.delete(tokenFromCookie);

    }
    public static void checkIfNeedDelayToken(HttpServletResponse response,HttpServletRequest request,StringRedisTemplate stringRedisTemplate) {

        String tokenFromCookie = CookieUtils.getCookieValueByName(request, cookike_key);
        if (!StringUtils.isEmpty(tokenFromCookie)) {
            try {
                String account = JwtUtil.parseValue(tokenFromCookie, token_key);
            } catch (ExpiredJwtException expiredJwtException) {


                ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
                String accountFromRedis = opsForValue.get(tokenFromCookie);
                if (!StringUtils.isEmpty(accountFromRedis)) {
                    log.info("关联数据未过期,符合展期条件,进行展期");

                    String refreshToken = createUserToken(accountFromRedis, response, stringRedisTemplate);
                    stringRedisTemplate.delete(tokenFromCookie);

                    CookieUtils.refreshRequestCookie(request, cookike_key, refreshToken);

                } else {
                    log.info("关联数据已过期过期,不进行展期");
                }

            } catch (Exception e){
                log.error("展期时未知异常",e);
                //忽略其它异常
            }
        }
    }




}
